﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Umi.Web.Utils.Utils
{
    /// <summary>
    /// 字符串工具类
    /// </summary>
    public static class StringUtils
    {
        /// <summary>
        /// 正则替换表达式，以prefix和suffix包裹的字符串
        /// </summary>
        /// <param name="args"></param>
        /// <param name="template"></param>
        /// <param name="prefix"></param>
        /// <param name="suffix"></param>
        /// <returns></returns>
        public static string ReplaceWithRegex(IDictionary<string, string> args, string template, string prefix = "[", string suffix = "]")
        {
            if (args == null)
                throw new ArgumentNullException(nameof(args));
            if (template == null)
                throw new ArgumentNullException(nameof(template));
            if (template == "")
                return "";
            prefix = prefix.Replace("\\", "\\\\").Replace("[", "\\[").Replace("]", "\\]");
            suffix = suffix.Replace("\\", "\\\\").Replace("[", "\\[").Replace("]", "\\]");
            string regex = $@"{prefix}([a-zA-Z0-9\-_]+){suffix}";
            return Regex.Replace(template, regex, match =>
            {
                if (args.ContainsKey(match.Groups[1].Value))
                    return args[match.Groups[1].Value];
                return "";
            }, RegexOptions.Multiline | RegexOptions.Compiled);
        }
    }
}
